const{ LinValidator, Rule }  = require('../../core/lin-validator-v2')
const {LoginType, ArtType} = require('../lib/enum')
const {User} = require('../models/user')

class PositiveIntegerValidator extends LinValidator{
  constructor() {
    super()
    // [] 且关系
    this.id = [
      new Rule('isInt', '需要是正整数', {min: 1})
    ]
  }
}

class RegisterValidator extends LinValidator{
  constructor() {
    super()
    // [] 且关系
    this.email = [
      new Rule('isEmail', '电子邮箱不符合规范，请输入正确的邮箱')
    ]
    this.password1 = [
      new Rule('isLength', '密码至少6个字符，最多32个字符', {
        min: 6,
        max: 32
      }),
      new Rule('matches', '密码不符合规范', "^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?![,\.#%'\+\*\-:;^_`]+$)[,\.#%'\+\*\-:;^_`0-9A-Za-z]{6,20}$")
    ]
    // 规则一个复制
    this.password2 = this.password1
    this.nickname = [
      new Rule('isLength', '昵称不符合长度规范', {
        min: 4,
        max: 32
      })
    ]
  }
  // 自定义校验， 必须以validate开头
  validatePassword(vals){
    let pwd1 = vals.body.password1
    let pwd2 = vals.body.password2
    if(pwd1 != pwd2) {
      throw new Error('两个密码不一致')
    }
  }
  // 异步函数,由于有一次查询数据库
  async validateEmail(vals) {
    const email = vals.body.email
    const user = await User.findOne({
      where: {
        email
      }
    })
    if (user) {
      throw new Error('邮箱已存在')
    }
  }
  


}

class TokenValidator extends LinValidator{
  constructor(){
    super()
    this.account = [
      new Rule('isLength', '不符合账号规则', {
        min: 4,
        max: 32
      })
    ]
    this.secret = [
      // 可传可不传
      new Rule('isOptional'),
      new Rule('isLength', '至少6个字符', {
        min: 6,
        max: 128
      })
    ]
  }
  async validateLoginType(vals) {
    if(!vals.body.type) {
      throw new Error('type是必须参数')
    }
    if(!LoginType.isThisType(vals.body.type)) {
      throw new Error('type参数不合法')
    }
  }
}

class NotEmptyValidate extends LinValidator{
  constructor(){
    super()
    this.token = [
      new Rule('isLength', '不允许为空', {
        min: 1
      })
    ]
  }
}

function checkArtType(vals) {
  let type = vals.body.type || vals.path.type
  if (!type) {
    throw new Error('type是必须参数')
  }
  type = parseInt(type)

  if (!ArtType.isThisType(type)) {
    throw new Error('type参数不合法')
  }
}

class LikeValidator extends PositiveIntegerValidator {
  constructor() {
    super()
    this.validateType = checkArtType
  }
}
const DislikeError = LikeValidator

class ClassicValidator extends LikeValidator {

}


module.exports = {
  PositiveIntegerValidator,
  RegisterValidator,
  TokenValidator,
  NotEmptyValidate,
  LikeValidator,
  DislikeError,
  ClassicValidator
}